package com.ruoyi.wx.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.wx.config.WxMaConfiguration;
import com.ruoyi.wx.config.WxMpConfiguration;
import com.ruoyi.wx.domain.WxApp;
import com.ruoyi.wx.domain.WxMaMsgForm;
import com.ruoyi.wx.domain.WxMpApp;
import com.ruoyi.wx.domain.WxMpMsgForm;
import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaSubscribeMessage;
import cn.binarywang.wx.miniapp.bean.WxMaSubscribeMessage.MsgData;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage.MiniProgram;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage.WxMpTemplateMessageBuilder;

@Component
public class WxMsgService {

	@Autowired
	private IWxAppService wxAppService;
	
	@Autowired
	private IWxMpAppService wxMpAppService;
	
	@Autowired
	private RedisCache redisCache;

	/**
	 * 发送微信小程序订阅消息
	 * @param msgForm
	 */
	public boolean sendSubscribeMsg(WxMaMsgForm msgForm) {
		if(StringUtils.isBlank(msgForm.getAppId())){
			return false;
		}
		WxMaSubscribeMessage.WxMaSubscribeMessageBuilder builder = WxMaSubscribeMessage.builder();
		//发送人openid
        builder.toUser(msgForm.getOpenId());
        //发送的模板id
        WxApp wxApp = wxAppService.getByAppid(msgForm.getAppId());
        if(wxApp == null){
        	return false;
        }
        builder.templateId(wxApp.getOneTemplateId());
        
        List<MsgData> dataList = new ArrayList<>();
        Map<String,String> dataMap = msgForm.getDataMap();
        for(String key : dataMap.keySet()){
        	//这里要完全按照订阅消息模板详情去设置，thing1 ，thing2...不能变
            MsgData data = new MsgData();
            data.setName(key);
            data.setValue(dataMap.get(key));
            dataList.add(data);
        }
        //消息主体
        builder.data(dataList);
        
        //点击订阅消息的跳转链接（默认是正式发布的小程序页面，当然也可以通过参数进行控制）
        builder.page(msgForm.getPage());
        
        WxMaSubscribeMessage msg = builder.build();
        try {
			WxMaService wxMaService = WxMaConfiguration.getMaServices().get(msgForm.getAppId());
            wxMaService.getMsgService().sendSubscribeMsg(msg);
            
            //redisCache.setCacheMapValue("userMapList", msgForm.getOpenId(), msgForm.getOpenId());
            //Long sum = redisCache.incr("sendSum");
            //System.out.println("发送成功第"+sum+"个");
            System.out.println("发送消息成功");
        } catch (Exception e) {
        	e.printStackTrace();
        	return false;
        }
        return true;
	}
	
	/**
	 * 发送微信公众号模板消息
	 * @param msgForm
	 */
	public boolean sendTemplateMsg(WxMpMsgForm msgForm){
		if(StringUtils.isBlank(msgForm.getWxId())){
			return false;
		}
		if(StringUtils.isBlank(msgForm.getOpenId())){
			return false;
		}
		WxMpApp mp = wxMpAppService.getWxMpAppByWxId(msgForm.getWxId());
		if(StringUtils.isBlank(mp.getOneTemplateId())){
			return false;
		}
		WxMpTemplateMessageBuilder builder = WxMpTemplateMessage.builder();
		//发送人openid
        builder.toUser(msgForm.getOpenId());
        //发送的模板id
        builder.templateId(mp.getOneTemplateId());
        
        List<WxMpTemplateData> dataList = new ArrayList<>();
        Map<String,String> dataMap = msgForm.getDataMap();
        for(String key : dataMap.keySet()){
        	//这里要完全按照订阅消息模板详情去设置，thing1 ，thing2...不能变
        	WxMpTemplateData data = new WxMpTemplateData();
            data.setName(key);
            data.setValue(dataMap.get(key));
            dataList.add(data);
        }
        //消息主体
        builder.data(dataList);
        
        //点击订阅消息的跳转链接（默认是正式发布的小程序页面，当然也可以通过参数进行控制）
        MiniProgram miniProgram = new MiniProgram();
        miniProgram.setAppid(msgForm.getAppId());
        miniProgram.setPagePath(msgForm.getPage());
        builder.miniProgram(miniProgram);
        
		WxMpTemplateMessage msg = builder.build();
		try {
			WxMpService wxMpService = WxMpConfiguration.getMpServices().get(mp.getAppId());
			wxMpService.getTemplateMsgService().sendTemplateMsg(msg);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}
	
	/**
	 * 发送微信公众号模板消息
	 * @param msgForm
	 */
	public boolean sendTemplateMsg(WxMpMsgForm msgForm, String templateId){
		if(StringUtils.isBlank(msgForm.getWxId())){
			return false;
		}
		if(StringUtils.isBlank(msgForm.getOpenId())){
			return false;
		}
		WxMpApp mp = wxMpAppService.getWxMpAppByWxId(msgForm.getWxId());
		WxMpTemplateMessageBuilder builder = WxMpTemplateMessage.builder();
		//发送人openid
        builder.toUser(msgForm.getOpenId());
        //发送的模板id
        builder.templateId(templateId);
        
        List<WxMpTemplateData> dataList = new ArrayList<>();
        Map<String,String> dataMap = msgForm.getDataMap();
        for(String key : dataMap.keySet()){
        	//这里要完全按照订阅消息模板详情去设置，thing1 ，thing2...不能变
        	WxMpTemplateData data = new WxMpTemplateData();
            data.setName(key);
            data.setValue(dataMap.get(key));
            dataList.add(data);
        }
        //消息主体
        builder.data(dataList);
        
        //点击订阅消息的跳转链接（默认是正式发布的小程序页面，当然也可以通过参数进行控制）
        MiniProgram miniProgram = new MiniProgram();
        miniProgram.setAppid(msgForm.getAppId());
        miniProgram.setPagePath(msgForm.getPage());
        builder.miniProgram(miniProgram);
        
		WxMpTemplateMessage msg = builder.build();
		try {
			WxMpService wxMpService = WxMpConfiguration.getMpServices().get(mp.getAppId());
			wxMpService.getTemplateMsgService().sendTemplateMsg(msg);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}
	
}
